package com.scs.application.modules.print.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.scs.application.consts.GlobalConsts;
import com.scs.application.core.exception.BusinessException;
import com.scs.application.core.query.QueryContext;
import com.scs.application.core.query.QueryContextHolder;
import com.scs.application.modules.base.annotation.MarkParameter;
import com.scs.application.modules.print.adapter.PrintTemplateAdapter;
import com.scs.application.modules.print.dto.TemplateDTO;
import com.scs.application.modules.print.entity.Field;
import com.scs.application.modules.print.entity.Template;
import com.scs.application.modules.print.service.TemplateService;
import com.scs.application.modules.sys.model.PageResult;
import com.scs.application.modules.sys.model.RestResult;
import com.google.common.collect.Lists;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 *
 */
@RestController
@RequestMapping("/print/template")
public class TemplateController{

    @Autowired
    private PrintTemplateAdapter printTemplateAdapter;

    @GetMapping("/getByBusKey/{busType}")
    public RestResult getByBusKey(@PathVariable(value = "busType") String busType) {
        TemplateDTO template = printTemplateAdapter.getTemplateService().getTemplateDTO(busType);
        return RestResult.ok("获取成功", template);
    }

    /**
     * 获取数据列表
     */
    @GetMapping("/page")
    public PageResult page() {
        QueryContext queryContext = QueryContextHolder.currentContext();
        IPage pageResult = printTemplateAdapter.getTemplateService().page(queryContext);
        return PageResult.ok("查询成功", pageResult.getRecords(), pageResult.getTotal());
    }

    @GetMapping("/list")
    public RestResult<List> list() {
        QueryContext queryContext = QueryContextHolder.currentContext();
        List result = printTemplateAdapter.getTemplateService().list(queryContext);
        return RestResult.ok("查询成功", result);
    }


    /**
     * 根据ID查找数据
     */
    @GetMapping("/find")
    public RestResult find(@RequestParam("id") Serializable id) {
        Template entity = printTemplateAdapter.getTemplateService().getById(id);
        if (entity == null) {
            return RestResult.error("数据查询失败<br>可能所操作数据已被删除，请刷新后重新尝试操作");
        }
        return RestResult.ok("获取数据成功", entity);
    }


    /**
     * 添加/更新数据
     */
    @PostMapping("/save")
    @MarkParameter(type = GlobalConsts.MarkParameterTYpe.PRINT_TEMPLATE,msg = "打印模板配置")
    public RestResult saveItem(@Valid @RequestBody Template entity) {
        boolean isOk = printTemplateAdapter.getTemplateService().saveOrUpdate(entity);
        if (!isOk) {
            return RestResult.error("数据保存失败");
        }
        return RestResult.ok("数据保存成功", entity);
    }

    /**
     * 删除数据
     */
    @DeleteMapping("/delete")
    @MarkParameter(type = GlobalConsts.MarkParameterTYpe.PRINT_TEMPLATE,msg = "打印模板配置")
    public RestResult deleteItems(@RequestBody Map<String, Object> para) {
        List<Serializable> ids = (List<Serializable>) para.get("ids");
        Boolean isOk = printTemplateAdapter.getTemplateService().removeCascadeByIds(ids);
        if (!isOk) {
            return RestResult.error("数据删除失败<br>可能所操作数据已被删除，请刷新页面重新尝试操作");
        }
        return RestResult.ok("数据删除成功");
    }

    /**
     * 获取字典比对
     *
     * @param busType 获取字典比对
     * @return
     */
    @GetMapping("/diff")
    public RestResult getTwoDictTypes(@RequestParam String busType) {
        TemplateService fileTemplateService = printTemplateAdapter.getTemplateService(false);
        if (fileTemplateService.getClass().getName().equals(printTemplateAdapter.getTemplateService().getClass().getName())) {
            throw new BusinessException("产品分支不支持该功能");
        }

        HashMap<String, Object> result = new HashMap<>();
        TemplateDTO fileTemplateDTO = fileTemplateService.getTemplateDTO(busType);
        result.put("productTemplateDTO", JSON.toJSONString(fileTemplateDTO));

        TemplateDTO templateDTO = printTemplateAdapter.getTemplateService().getTemplateDTO(busType);
        result.put("projectTemplateDTO", JSON.toJSONString(templateDTO));
        return RestResult.ok("获取数据成功", result);
    }

    /**
     * 添加/更新数据
     */
    @PostMapping("/saveDTO")
    @MarkParameter(type = GlobalConsts.MarkParameterTYpe.PRINT_TEMPLATE,msg = "打印模板配置")
    public RestResult saveDTO(@Valid @RequestBody TemplateDTO entity) {
        Template template = new Template();
        BeanUtils.copyProperties(entity, template);
        boolean isOk = printTemplateAdapter.getTemplateService().saveOrUpdate(template);
        if (!isOk) {
            return RestResult.error("数据保存失败");
        }
        if (entity.getFieldDTOS() != null && !entity.getFieldDTOS().isEmpty()) {
            List<Field> fields = Lists.newArrayList();
            for (TemplateDTO.FieldDTO fieldDTO : entity.getFieldDTOS()) {
                Field field = new Field();
                BeanUtils.copyProperties(fieldDTO, field);
                fields.add(field);
            }
            printTemplateAdapter.getFieldService().saveOrUpdateBatch(fields);
        }
        return RestResult.ok("数据保存成功", entity);
    }

    //列表，带字段
    @GetMapping("/listWithField")
    public RestResult listWithField() {
        QueryContext queryContext = QueryContextHolder.currentContext();
        List<Template> list = (List<Template>) printTemplateAdapter.getTemplateService(true).list(queryContext);
        if (list != null) {
            List<Field> fieldListAll = printTemplateAdapter.getFieldService().list();
            if (fieldListAll != null && fieldListAll.size() > 0) {
                for(Template template : list) {
                    template.setFieldList(fieldListAll.stream().filter(ob -> ob.getTemplateId().equals(template.getId())).collect(Collectors.toList()));
                }
            }
        }
        return RestResult.ok("查询成功", list);
    }
}
